import axios from 'axios'
import request from '@neu/biz-core/utils/request'
import { getToken } from '@neu/biz-core/utils/auth'

export const pageByBizdef = (bizdefId) => {
  const url = '/cmdb/bizs/bizdef/' + bizdefId + '/page'
  return (params) => {
    return request({
      url: url,
      params,
      method: 'get'
    })
  }
}

export const detail = (id) => {
  return request({
    url: '/cmdb/bizs/' + id,
    method: 'get'
  })
}

export const batchUpdateOneAttr = (bizdefId, attrKey, attrVal) => {
  return request({
    url: '/cmdb/bizs/batch/' + bizdefId + '/' + attrKey,
    data: { value: attrVal },
    method: 'put'
  })
}

export const update = (id, data) => {
  return request({
    url: '/cmdb/bizs/' + id,
    data: data,
    method: 'put'
  })
}

export const create = (data) => {
  return request({
    url: '/cmdb/bizs',
    data: data,
    method: 'post'
  })
}

export const remove = (id) => {
  return request({
    url: '/cmdb/bizs/' + id,
    method: 'delete'
  })
}

export const batchRemove = (ids) => {
  return request({
    url: '/cmdb/bizs/batch',
    data: { ids },
    method: 'delete'
  })
}

export const exportByBizdef = (bizdefId, params) => {
  const url = '/cmdb/bizs/bizdef/' + bizdefId + '/export'
  return new Promise((resolve, reject) => {
    axios.get(url, { params, responseType: 'blob', headers: { 'Authentication': getToken() }})
      .then(response => {
        resolve(response)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export const updateAttr = (instanceId, attrKey, attrVal) => {
  return request({
    url: '/cmdb/bizs/' + instanceId + '/' + attrKey,
    data: { value: attrVal },
    method: 'put'
  })
}

export const getRelations = (id) => {
  const url = '/cmdb/bizs/' + id + '/relations'
  return () => {
    return request({
      url: url,
      method: 'get'
    })
  }
}

export const removeRelation = (instanceId) => {
  const urlPrefix = '/cmdb/bizs/' + instanceId + '/relations/'
  return (relationId) => {
    const url = urlPrefix + relationId
    return request({
      url: url,
      method: 'delete'
    })
  }
}

export const listByBizdef = (bizdefId) => {
  const url = '/cmdb/bizs/bizdef/' + bizdefId
  return request({
    url: url,
    method: 'get'
  })
}

export const addRelation = (instanceId, data) => {
  return request({
    url: '/cmdb/bizs/' + instanceId + '/relations/add',
    data,
    method: 'put'
  })
}

export const getTopo = (instanceId) => {
  return request({
    url: '/cmdb/bizs/' + instanceId + '/topo',
    method: 'get'
  })
}
